package com.mooc.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

public class ServerTest {

    public static void main(String[] args) {

        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader bufferedReader = null;
        PrintStream printStream = null;

        try {
            serverSocket = new ServerSocket(8888);
            socket = serverSocket.accept();

            System.out.println("Client connect!");

            bufferedReader = new BufferedReader(
                    new InputStreamReader(
                            socket.getInputStream()));
            printStream = new PrintStream(socket.getOutputStream());

            while (true) {
                String message = bufferedReader.readLine();
                System.out.println("客户端发送来的字符是：" + message);
                if ("bye".equalsIgnoreCase(message)) {
                    System.out.println("客户端已下线");
                    break;
                }
                printStream.println("I received!");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != printStream) printStream.close();
                if (null != bufferedReader) bufferedReader.close();
                if (null != socket) socket.close();
                if (null != serverSocket) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
